# -*- coding: utf-8 -*-

class ProductController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:getProductCount,:getPricesById,:getPricesBySTIdPIds,:copyProduct,:copyToNew]
  
  #产品设置主页
  #同时得到所有根目录下的产品总数目
  def productsList
    @totalCount = Product.count
    logger.info @totalCount
  end

  #显示添加产品页面
  def newProduct

  end

  #显示编辑产品页面
  def editProduct
    @productId = params[:id]
  end
  
  #复制产品页面
  def copyProduct
    @productId = params[:id]
  end

  #得到
  def getProductCount
    conditionsStr = nil
    conditionsHash = Hash.new
    if params[:name] != nil && params[:name] != ''
      conditionsStr = 'name like :name'
      conditionsHash[:name] = '%' + params[:name] + '%'
    end

    if params[:product_type_id] != nil
      if conditionsStr.nil?
        conditionsStr = 'product_type_id = :product_type_id'
      else
        conditionsStr = conditionsStr + ' AND product_type_id = :product_type_id'        
      end
      conditionsHash[:product_type_id] = params[:product_type_id]
    end

    if params[:brand_id] != nil
      if conditionsStr.nil?
        conditionsStr = 'brand_id = :brand_id'
      else
        conditionsStr = conditionsStr + ' AND brand_id = :brand_id'        
      end
      conditionsHash[:brand_id] = params[:brand_id]
    end

    if conditionsStr == nil
      totalCount = Product.select(:id).count
    else
      totalCount = Product.select(:id).where([conditionsStr,conditionsHash]).count
    end

    render :text=>totalCount, :layout=>false
  end
  
  def getTreeData    
    begin
      #nodeId =  params["node_id"]
      nodeId =  params["node"]
      #如果nodeId=xnode-47或nil或其它非XX_YY组成的值，则说明他是根。
      #只要带有xnode-后面加数字的，都要清0
      if nodeId == nil || (nodeId.include? "xnode-") || nodeId == "0" || nodeId == "NaN" || nodeId == 0
        is_root = true
        nodeId = 0
      end

      #提取真正的ID
      logger.info "Realy nodeId....................................................."
      oriNodeId = "" #让它变为空字符串，这时说明，用点刷新的节点直接挂在根上。
      if nodeId !=0
        if (nodeId.include? "_")
          oriNodeId = nodeId + "_"
          treeNodeIdArray = nodeId.split("_")
          nodeId = treeNodeIdArray[treeNodeIdArray.size-1]
        else
          #这儿也是一个要判断根的地方
          is_root = true
        end
      end

      conditionsStr = nil
      conditionsHash = Hash.new
      if params[:name] != nil && params[:name] != ''
        conditionsStr = '(name like :name OR number like :name)'
        conditionsHash[:name] = '%' + params[:name] + '%'
      end

      if params[:product_type_id] != nil
        if conditionsStr.nil?
          logger.info "conditionsStr"          
          conditionsStr = 'product_type_id = :product_type_id'          
          logger.info conditionsStr
        else
          conditionsStr = conditionsStr + ' AND product_type_id = :product_type_id'
        end
        conditionsHash[:product_type_id] = params[:product_type_id]
      end

      if params[:brand_id] != nil
        if conditionsStr.nil?
          logger.info "conditionsStr"
          conditionsStr = 'brand_id = :brand_id'
          logger.info conditionsStr
        else
          conditionsStr = conditionsStr + ' AND brand_id = :brand_id'
        end
        conditionsHash[:brand_id] = params[:brand_id]
      end
      
      treeData="["
      #第一个If是得到根下的产品
      if nodeId == nil || nodeId == 0
       
        if conditionsStr == nil
          products = Product.includes([:brand,:product_type,:components]).offset(params[:start]).limit(params[:limit].to_i)
        else
          products = Product.where([conditionsStr,conditionsHash]).includes([:brand,:product_type,:components]).offset(params[:start].to_i).limit(params[:limit].to_i)
        end
        
        products.each do |product|
          brandName = ""
          if !product.brand.nil?
            brandName = product.brand.name
          end
          if !product.product_type.nil?
            productType = product.product_type.name
          end
          treeData.concat("{id:#{product.id},name:#{product.name.to_json},brand_name:#{brandName.to_json},product_type:#{productType.to_json},spec:#{product.spec.to_json},unit_price:'#{product.unit_price}',number:#{product.number.to_json},description:#{product.description.to_json},created_at:'#{(product.created_at+3600*8).strftime("%Y-%m-%d %H:%M")}',updated_at:'#{(product.updated_at+3600*8).strftime("%Y-%m-%d %H:%M")}',")
          if product.components.length > 0
            treeData.concat("leaf:false,iconCls:'task-folder'")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:false},")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:false,spec:'#{product.spec}',unit_price:'#{product.unit_price}',number:unit_price:'#{product.number}'},")
          else
            treeData.concat("iconCls:'task',leaf:true")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:true},")
            #treeData.concat("{id:#{product.id},name:\"#{product.name}\",leaf:true,spec:'#{product.spec}',unit_price:'#{product.unit_price}'},")
          end
          treeData.concat("},")
        end
      else
        #以下情况，都是触发了“分支”引发expand后要操作的代码。
        product = Product.find(nodeId,:include=>[:products_components=>:component])
        #product = Product.find(:include=>["products_components"],:conditions=>["id = ?",nodeId])
        productsComponents = product.products_components
        productsComponents.each do |productComponent|
          #加“_”的原因是在树中不能有重复的ID，所以要用爷子节点的ID组合来实现。
          #如果它的父节点是根。
          if is_root
            oriNodeId = nodeId.to_s + "_"
          end
          brandName = ""
          if !productComponent.component.brand.nil?
            brandName = productComponent.component.brand.name
          end
          if !productComponent.component.product_type.nil?
            productType = productComponent.component.product_type.name
          end
          treeData.concat("{id:'#{oriNodeId}#{productComponent.component.id}',name:#{productComponent.component.name.to_json},brand_name:#{brandName.to_json},product_type:#{productType.to_json},spec:#{productComponent.component.spec.to_json},unit_price:#{productComponent.component.unit_price},quantity:'#{productComponent.quantity}',number:#{productComponent.component.number.to_json},description:#{product.description.to_json},created_at:'#{(product.created_at+3600*8).strftime("%Y-%m-%d %H:%M")}',updated_at:'#{(product.updated_at+3600*8).strftime("%Y-%m-%d %H:%M")}',")
          #if productComponent.component.components.length > 0,另换一种判断方法
          if productComponent.component.is_suit == 1
            treeData.concat("leaf:false,iconCls:'task-folder'")
          else
            treeData.concat("iconCls:'task',leaf:true")
          end
          treeData.concat("},")
        end
      end
      
      
      if treeData.length > 1
        treeData = treeData[0,treeData.size-1]
      end
      treeData.concat("]")

      render :text=>treeData, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end
  
  def getAllProducts
    forCBB = params[:for_cbb]
    if forCBB != 'true' && forCBB != 'true_simple'
      forCBB = 'false'
    end
    
    start = params[:start]
    limit = params[:limit]
    
    if params[:query].nil? || params[:query] == "请选择产品"
      queryStr = ""
    else
      queryStr = params[:query]
    end

    if params[:is_suit]==nil
      products = Product.name_like queryStr
    elsif params[:is_suit].to_i == 1
      products = Product.name_like(queryStr).merge(Product.is_suit)
    elsif params[:is_suit].to_i == 0
      products = Product.name_like(queryStr).merge(Product.is_not_suit)
    end
    
    productsNow = products.paginate start,limit
    if forCBB == 'false'
      jsonStr="{totalProperty:"+products.length.to_s+",root:"+productsNow.to_json()+"}"
    elsif forCBB == 'true'
      jsonStr="{totalProperty:"+products.length.to_s+",root:"+productsNow.to_json(:only=>[:id,:name,:number,:spec,:unit_price,:unit,:is_suit])+"}"
    elsif forCBB == 'true_simple'
      jsonStr="{totalProperty:"+products.length.to_s+",root:"+productsNow.to_json(:only=>[:id,:name,:number,:is_suit])+"}"
    end
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到所有的套组
  def getAllSuitProducts
    start = params[:start]
    limit = params[:limit]
    suitProductsTotal = Product.where("is_suit = 1 AND name like ?","%"+params[:query]+"%")
    suitProducts = suitProductsTotal.offset(start.to_i).limit(limit.to_i)
    jsonStr="{totalProperty:"+suitProductsTotal.length.to_s+",root:"+suitProducts.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  #得到某一个产品的所有下属产品，这个方法，基本已经作费了。
  #def getSubProductsById
  #  components = ProductsComponent.all(:conditions=>["component_id = ?",params[:id]])
  #  products = []
  #  components.each do |component|
  #    products << component.product
  #  end
  #  jsonStr="{totalProperty:"+products.length.to_s+",root:"+products.to_json()+"}"
  #  render :text=>jsonStr, :layout=>false
  #end

  #得到某产品下的所有直接组件。
  def getAllComponentsById
    begin            
      productId = params[:id]
      logger.info productId
      components = ProductsComponent.where("product_id = ?",productId.to_i).includes([:component])
      jsonStr="{totalProperty:"+components.length.to_s+",root:"+components.to_json(:include=>[:component])+"}"
      #logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info(e)
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end  
  end

  def create
    begin            
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      
      isSuit = paramsHash["is_suit"]
      logger.info "Suit............................................."
      logger.info isSuit
      product = Product.new()
      product.company_id = session[:company_id]
      product.vendor_id = paramsHash["vendor_id"]
      product.brand_id = paramsHash["brand_id"]
      product.product_type_id = paramsHash["product_type_id"]
      product.number = paramsHash["number"]
      product.name = paramsHash["name"]
      
      #判断一下，是否已经有重复的产品出现
      oldProduct = Product.where("name = ?",product.name.strip).first
      if oldProduct != nil
        info="已经有相同名称的产品存在！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end

      oldProduct = Product.where("number = ?",product.number.strip).first
      if oldProduct != nil
        info="已经有相同编号的产品存在！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end
      
      product.bar_code = paramsHash["bar_code"]
      product.spec = paramsHash["spec"]
      product.unit = paramsHash["unit"]
      product.unit_price = paramsHash["unit_price"]
      product.min_quantity = paramsHash["min_quantity"]
      product.max_quantity = paramsHash["max_quantity"]
      product.description = paramsHash["description"]
      product.is_suit = paramsHash["is_suit"]
      product.is_sale = paramsHash["is_sale"]
      #有会计权限的人才可以保存成本相关信息
      if session[:financial_management] == '是'
        product.tax_price = paramsHash["tax_price"]
        product.cost_price = paramsHash["cost_price"]
      end
      #根据前在组件的值设置的不同，可能是1或"1"
      if isSuit == "1" || isSuit == 1
        productsHashArray = paramsHash["products"]
        productsHashArray.each do |productHash|
          productsComponent = ProductsComponent.new
          productsComponent.component_id = productHash["product_id"]
          productsComponent.quantity = productHash["quantity"]
          product.products_components << productsComponent
        end       
      end

      Product.transaction do
        product.save!
        #处理根据销售类型制定的多个价格
        pricesHashArray = paramsHash["prices"]
        pricesHashArray.each do |priceHash|
          productPrice = ProductPrice.new
          productPrice.company_id = session[:company_id]
          productPrice.department_id = session[:department_id]
          productPrice.employee_id = session[:employee_id]
          productPrice.sale_type_id = priceHash["id"].to_i
          productPrice.product_id = product.id
          productPrice.unit_price = priceHash["unit_price"].to_f
          productPrice.save!
        end
      end
      info = "成功"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end    
  end

  #编辑产品前的准备工作。
  def editProduct    
    @productId = params[:id]
  end

  #编辑前的数据准备
  def edit
    
    product = Product.find(params[:id])
    #有会计权限的人才可以保存成本相关信息
    if session[:financial_management] != '是'
      product.tax_price = 0.00
      product.cost_price = 0.00
    end 
    #rootStr = product.to_json(:include=>[:vendor])
    rootStr = product.to_json(:include=>{:vendor=>{:only=>[:id,:name]},:brand=>{:only=>[:id,:name]},:product_type=>{:only=>[:id,:name]}})
    
    jsonStr = "{root:["+rootStr+"]}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #把编辑后的数据，更新到数据库中
  def update
    begin      
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      isSuit = paramsHash["is_suit"]
      id = paramsHash["id"]
      logger.info "Suit............................................."
      logger.info isSuit
      product = Product.find(id)      
      product.vendor_id = paramsHash["vendor_id"]
      product.brand_id = paramsHash["brand_id"]
      product.product_type_id = paramsHash["product_type_id"]
      
      #判断一下，是否已经有重复的产品出现
      if product.number != paramsHash["number"].strip
        oldProduct = Product.where("number = ?",paramsHash["number"].strip).first
        if oldProduct != nil
          info="已经有相同编号的产品存在！"
          result = "{success:true,info:'#{info}'}"
          render :text=>result, :layout=>false and return false
        end
      end

      if product.name != paramsHash["name"].strip
        oldProduct = Product.where("name = ?",paramsHash["name"].strip).first
        if oldProduct != nil
          info="已经有相同的名称的产品存在！"
          result = "{success:true,info:'#{info}'}"
          render :text=>result, :layout=>false and return false
        end
      end
      
      product.number = paramsHash["number"]
      product.name = paramsHash["name"]
      product.bar_code = paramsHash["bar_code"]
      product.spec = paramsHash["spec"]
      product.unit = paramsHash["unit"]
      product.unit_price = paramsHash["unit_price"]
      product.min_quantity = paramsHash["min_quantity"]
      product.max_quantity = paramsHash["max_quantity"]
      product.description = paramsHash["description"]
      product.is_suit = paramsHash["is_suit"]
      product.is_sale = paramsHash["is_sale"]
      #有会计权限的人才可以保存成本相关信息
      if session[:financial_management] == '是'
        product.tax_price = paramsHash["tax_price"]
        product.cost_price = paramsHash["cost_price"]
      end   
      Product.transaction do
        if isSuit == "1" || isSuit == 1
          productsHashArray = paramsHash["products"]
          #删除已经有的component从新添加，以节省判断。
          ProductsComponent.delete_all(["product_id = ?",id])
          productsHashArray.each do |productHash|
            productsComponent = ProductsComponent.new
            productsComponent.component_id = productHash["product_id"]
            productsComponent.quantity = productHash["quantity"]
            product.products_components << productsComponent
          end
        end

        #处理根据销售类型制定的多个价格
        pricesHashArray = paramsHash["prices"]
        pricesHashArray.each do |priceHash|
          if priceHash["product_price_id"] == nil || priceHash["product_price_id"] == ""
            productPrice = ProductPrice.new
            productPrice.company_id = session[:company_id]
            productPrice.department_id = session[:department_id]
            productPrice.employee_id = session[:employee_id]
            productPrice.sale_type_id = priceHash["id"].to_i
            productPrice.product_id = product.id
            productPrice.unit_price = priceHash["unit_price"].to_f
            productPrice.save!
          else
            productPrice = ProductPrice.find(priceHash["product_price_id"].to_i)
            productPrice.department_id = session[:department_id]
            productPrice.employee_id = session[:employee_id]
            productPrice.sale_type_id = priceHash["id"].to_i
            productPrice.product_id = product.id
            productPrice.unit_price = priceHash["unit_price"].to_f
            productPrice.save!
          end
        end        
        product.save!
      end
      info = "成功"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info(e)
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end    
  end
  
  #根据复制,生成新产品
  def copyToNew
    begin      
      paramsHash = Util.paramsPreprocessToHash(params[:data])
      isSuit = paramsHash["is_suit"]
      id = paramsHash["id"]
      product = Product.new
      product.company_id = session[:company_id]
      product.vendor_id = paramsHash["vendor_id"]
      product.brand_id = paramsHash["brand_id"]
      product.product_type_id = paramsHash["product_type_id"]
      
      #判断一下，是否已经有重复的产品出现
      oldProduct = Product.where("number = ?",paramsHash["number"].strip).first
      if oldProduct != nil
        info="已经有相同编号的产品存在！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end

      oldProduct = Product.where("name = ?",paramsHash["name"].strip).first
      if oldProduct != nil
        info="已经有相同的名称的产品存在！"
        result = "{success:true,info:'#{info}'}"
        render :text=>result, :layout=>false and return false
      end     
      
      product.number = paramsHash["number"]
      product.name = paramsHash["name"]
      product.bar_code = paramsHash["bar_code"]
      product.spec = paramsHash["spec"]
      product.unit = paramsHash["unit"]
      product.unit_price = paramsHash["unit_price"]
      product.min_quantity = paramsHash["min_quantity"]
      product.max_quantity = paramsHash["max_quantity"]
      product.description = paramsHash["description"]
      product.is_suit = paramsHash["is_suit"]
      product.is_sale = paramsHash["is_sale"]
      #有会计权限的人才可以保存成本相关信息
      if session[:financial_management] == '是'
        product.tax_price = paramsHash["tax_price"]
        product.cost_price = paramsHash["cost_price"]
      end   
      Product.transaction do
        product.save!        
        if isSuit == "1" || isSuit == 1
          productsHashArray = paramsHash["products"]
          productsHashArray.each do |productHash|
            productsComponent = ProductsComponent.new
            productsComponent.component_id = productHash["product_id"]
            productsComponent.quantity = productHash["quantity"]
            product.products_components << productsComponent
          end
        end

        #处理根据销售类型制定的多个价格
        pricesHashArray = paramsHash["prices"]
        pricesHashArray.each do |priceHash|
          productPrice = ProductPrice.new
          productPrice.company_id = session[:company_id]
          productPrice.department_id = session[:department_id]
          productPrice.employee_id = session[:employee_id]
          productPrice.sale_type_id = priceHash["id"].to_i
          productPrice.product_id = product.id
          productPrice.unit_price = priceHash["unit_price"].to_f
          productPrice.save!
        end        
        product.save!
      end
      info = "成功"
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end    
  end

  def destroy
    id = params[:id]
    product = Product.find(id)
    #要删除它，要有个前提，1.没有人引用它，2.没有订单引用它。
    childProducts = ProductsComponent.where(component_id:id)
    collectionProducts = ProductCollection.where(product_id:id)
    if  childProducts.length == 0 && collectionProducts.length == 0
      product.destroy()
      #同时删除所有的和这个产品相关的子产品
      ProductsComponent.delete_all("product_id = #{id}")
      info = "删除成功。"
    else
      info = "你要删除的产品有套组引用或订单引用，不能删除。"
    end

    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到根据销售类型得到的所有产品价格
  def getPricesById
    productId = params[:id]
    if productId.nil? || productId == "0" || productId == 0
      productPrices = SaleType.select([:id,:name]).where("is_locked = 0")
    else
      productPrices = SaleType.select("st.id ,st.name,pp.id as product_price_id,pp.unit_price").joins("st left join product_prices pp on st.id = pp.sale_type_id AND pp.product_id = #{productId} where st.is_locked = 0")
    end
    jsonStr="{totalProperty:"+productPrices.length.to_s+",root:"+productPrices.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据saleTypeId,product_ids串，得到这些产品对应的销售类型的价格
  def getPricesBySTIdPIds
    saleTypeId = params[:sale_type_id]
    productIds = params[:product_ids].split(/,/)
    productPrices = ProductPrice.select([:product_id,:unit_price]).where("sale_type_id = ? AND product_id in (?) AND company_id = ? AND unit_price <> -1",saleTypeId,productIds,session[:company_id]);
    jsonStr="{totalProperty:"+productPrices.length.to_s+",root:"+productPrices.to_json()+"}"
    #logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
end
